package com.adtech.farmProducts.activities.fragment.dialog;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.vise.log.ViseLog;
import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.widgets.load.LoadFactory;
import com.adtech.common.widgets.load.core.LoadManager;
import com.adtech.common.widgets.load.view.AbsView;
import com.adtech.common.widgets.recycler.RecyclerViewAdapter;
import com.adtech.common.widgets.recycler.decoration.DividerItemDecoration;
import com.adtech.common.widgets.view.PinyinUtils;
import com.adtech.common.widgets.view.SideBar;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.adapter.CityAdapter;
import com.adtech.farmProducts.adapter.ProvinceAdapter;
import com.adtech.farmProducts.model.ProvinceInfo;
import com.adtech.farmProducts.utils.MoveToPostion;
import com.adtech.farmProducts.utils.PinyinComparator;
import com.adtech.farmProducts.widget.EmptyView;
import com.adtech.farmProducts.widget.ErrorView;
import com.adtech.farmProducts.widget.LoadingView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * Descr: 机构选择-列表
 */

public class SelectCityDialogFragment extends DialogFragment implements View.OnClickListener {

    private OnUpdateListener mOnUpdateListener;

    private TextView tvTitle, tvAll;
    private RecyclerView mRecyclerView;
    private SideBar sideBar;
    private TextView dialog;
    private LinearLayout layoutCity;
    private RecyclerView mCityRecyclerView;

    private ProvinceAdapter mAdapter;
    private CityAdapter mCityAdapter;
    private LoadManager mLoadManager;
    private static boolean isCheck;

    /**
     * 显示更新头像的dialog
     *
     * @param isChecks 是否可以多选
     */
    public static SelectCityDialogFragment newInstance(OnUpdateListener mOnUpdateListener, boolean isChecks) {
        SelectCityDialogFragment updateDialogFragment = new SelectCityDialogFragment();
        updateDialogFragment.setOnItemViewClickListener(mOnUpdateListener);
        isCheck = isChecks;
        return updateDialogFragment;
    }


    /**
     * 初始化接口监听对象
     */
    private void setOnItemViewClickListener(OnUpdateListener onUpdateListener) {
        mOnUpdateListener = onUpdateListener;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 设置无标题栏
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 加载界面布局
        View view = inflater.inflate(R.layout.dialog_select_config, container, false);
        initView(view);//设置背景透明，才能显示出layout中诸如圆角的布局，否则会有白色底（框）
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initView(View view) {
        tvTitle = view.findViewById(R.id.tv_title);
        tvAll = view.findViewById(R.id.tv_all);
        mRecyclerView = view.findViewById(R.id.recycler_view);
        sideBar = view.findViewById(R.id.side_bar);
        dialog = view.findViewById(R.id.dialog);
        layoutCity = view.findViewById(R.id.layout_city);
        mCityRecyclerView = view.findViewById(R.id.recycler_view_city);
        view.findViewById(R.id.iv_clear).setOnClickListener(this);
    }

    private void initData() {
        tvTitle.setText("选择");
        tvAll.setText("全省");
        sideBar.setTextView(dialog);
        mLoadManager = LoadFactory.getInstance().register(mRecyclerView, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                getProvinceList();
            }
        });
        orgListInit();
        getProvinceList();
    }

    private String areaId;

    /**
     * 初始化机构列表
     */
    private void orgListInit() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL, R.drawable.shape_divider_line, 16, false));

        mCityRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mCityRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL, R.drawable.shape_divider_line, 16, false));
        mAdapter = new ProvinceAdapter(new RecyclerViewAdapter.AdapterListenerImpl<ProvinceInfo>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<ProvinceInfo> holder, ProvinceInfo data) {
                super.onItemClick(holder, data);
                tvTitle.setText(data.getName());
                areaId = data.getId();
                getCityList(data.getId());
            }
        });
        mCityAdapter = new CityAdapter(new RecyclerViewAdapter.AdapterListenerImpl<ProvinceInfo>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<ProvinceInfo> holder, ProvinceInfo data) {
                super.onItemClick(holder, data);
                tvTitle.setText(data.getName());
                returnValue(data);
            }
        });
        mAdapter.isCheck(isCheck);
        mRecyclerView.setAdapter(mAdapter);
        mCityAdapter.isCheck(isCheck);
        mCityRecyclerView.setAdapter(mCityAdapter);
    }


    /**
     * 获取省份列表
     */
    private void getProvinceList() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("areaCode", AccountManagers.getToken());
        okHttpClient.post(Common.Constant.API_IP + "api/Common/getProvinceList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<ProvinceInfo>>>() {
                }.getType();
                RspModel<List<ProvinceInfo>> rspModel = getAnalysisBase(mLoadManager, response, type, "获取省份列表");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            List<ProvinceInfo> orgList = filledData(rspModel.getData());
                            Collections.sort(orgList, new PinyinComparator());
                            mAdapter.replace(orgList);
                            initEvents();//触摸监听
                        } else {
                            mLoadManager.showStateView(EmptyView.class);
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 获取城市列表
     */
    private void getCityList(String proviceId) {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("province_areaid", proviceId);
        okHttpClient.post(Common.Constant.API_IP + "api/Common/getCityList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<ProvinceInfo>>>() {
                }.getType();
                RspModel<List<ProvinceInfo>> rspModel = getAnalysisBase(mLoadManager, response, type, "获取省份列表");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            layoutCity.setVisibility(View.VISIBLE);
                            List<ProvinceInfo> orgList = filledData(rspModel.getData());
                            Collections.sort(orgList, new PinyinComparator());
                            mCityAdapter.replace(orgList);
                        } else {
                            mLoadManager.showStateView(EmptyView.class);
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.gravity = Gravity.BOTTOM;
        window.setAttributes(layoutParams);

        //设置背景半透明
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //getDialog().setCancelable(false);//这个会屏蔽掉返回键

        View decorView = window.getDecorView();
        decorView.setPadding(0, 0, 0, 0);
        decorView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
//                    close();
                }
                return true;
            }
        });
    }

    /**
     * 返回数据
     */
    private void returnValue(ProvinceInfo data) {
        if (mOnUpdateListener != null) {
            data.setParentId(areaId);
            mOnUpdateListener.returnValue(data);
            close();
        }
    }

    /**
     * 返回选中多个数据
     */
    private void returnListValue(List<ProvinceInfo> list) {
        if (mOnUpdateListener != null) {
            mOnUpdateListener.returnListValue(list);
            close();
        }

    }

    /**
     * 关闭dialog
     */
    private void close() {
        if (getDialog() != null && getDialog().isShowing()) {
            dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add_index:
                List<ProvinceInfo> list = mAdapter.getDataList();
                List<ProvinceInfo> orgList = new ArrayList<>();
                for (ProvinceInfo target : list) {
                    if (target.isSelected()) {
                        orgList.add(target);
                    }
                }
                returnListValue(orgList);
                break;
            case R.id.iv_clear:
                close();
                break;
            case R.id.check_all:
                break;
        }
    }

    /**
     * 定义一个item点击事件的接口回调监听
     */
    public interface OnUpdateListener {
        void returnValue(ProvinceInfo data);

        void returnListValue(List<ProvinceInfo> list);
    }

    private void initEvents() {
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    MoveToPostion.moveToPosition(mRecyclerView, position);
                }
            }
        });
    }

    /**
     * 数据排序
     */
    private List<ProvinceInfo> filledData(List<ProvinceInfo> date) {
        List<ProvinceInfo> mSortList = new ArrayList<>();
        ArrayList<String> indexString = new ArrayList<>();

        for (int i = 0; i < date.size(); i++) {
            ProvinceInfo sortModel = date.get(i);
            String pinyin = PinyinUtils.getPingYin(date.get(i).getName());
            String sortString = pinyin.replace("zhongqing", "chongqing").substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
                if (!indexString.contains(sortString)) {
                    indexString.add(sortString);
                }
            } else {//不是汉字时 默认#
                sortModel.setSortLetters("#");
            }
            mSortList.add(sortModel);
        }
        Collections.sort(indexString);
        indexString.add("#");
        sideBar.setIndexText(indexString);
        return mSortList;
    }

    /**
     * 数据解析
     *
     * @param response 数据源
     * @param type     class
     * @param log      log
     * @param <T>      泛型
     * @return 结果
     */
    public <T> RspModel<T> getAnalysisBase(LoadManager mLoadManager, AsyncHttpResponse response, Type type, String log) {
        ViseLog.d(response.toString());
        switch (response.getCode()) {
            case 200:
                try {
                    RspModel<T> rspModel = new Gson().fromJson(response.getBody(), type);
                    ViseLog.e(log + rspModel.toString());
                    switch (rspModel.getCode()) {
                        case 200:
                            mLoadManager.showSuccessView();
                            return rspModel;
                        default:
                            App.getInstance().showMessage(rspModel.getMessage());
                            mLoadManager.showStateView(EmptyView.class);
                            break;
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    mLoadManager.showStateView(ErrorView.class);
                }
                break;
            default:
                mLoadManager.showStateView(EmptyView.class);
                break;
        }
        return null;
    }
}
